package com.uflower.user.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.uflower.common.utils.PageUtils;
import com.uflower.common.utils.Query;
import com.uflower.user.dao.UserDao;
import com.uflower.user.entity.UserEntity;
import com.uflower.user.service.UserService;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;


import java.util.HashMap;
import java.util.Map;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {
    /**
     * 根据用户名，查询系统用户
     *
     * @param username
     */
    @Override
    public UserEntity queryByUserName(String username) {
        return baseMapper.queryByUserName(username);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String username = (String)params.get("username");

        IPage<UserEntity> page = this.page(
                new Query<UserEntity>().getPage(params),
                new QueryWrapper<UserEntity>()
                        .like(StringUtils.isNotBlank(username),"username", username)
        );
        return new PageUtils(page);
    }

    @Override
    public void updateStatus(UserEntity user) {
        this.updateById(user);
        if (!StringUtils.isEmpty(user.getUsername())) {
            this.update(user,new QueryWrapper<UserEntity>().eq("id",user.getId()));
        }
    }

    /**
     * 生成token
     *
     * @param userId 用户ID
     */
    @Override
    public String createToken(long userId,String username) {
        DateTime now = DateTime.now();
        DateTime newTime = now.offsetNew(DateField.MINUTE, 10);

        Map<String,Object> payload = new HashMap<String,Object>();
        //签发时间
        payload.put(JWTPayload.ISSUED_AT, now);
        //过期时间
        payload.put(JWTPayload.EXPIRES_AT, newTime);
        //生效时间
        payload.put(JWTPayload.NOT_BEFORE, now);
        //载荷
        payload.put("id", userId);
        payload.put("username", username);

        String key = "uflower";
        return JWTUtil.createToken(payload, key.getBytes());
    }


    /**
     * 获取图片验证码
     *
     */
    @Override
    public LineCaptcha getCaptcha() {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(90, 35,4,30);
        // 自定义验证码内容为四则运算方式
//        lineCaptcha.setGenerator(new MathGenerator());
        // 重新生成code
        lineCaptcha.createCode();
        return lineCaptcha;
    }


}